package org.zizi.db.esql;

import java.sql.PreparedStatement;
import java.util.Arrays;
import java.util.List;

import org.zizi.db.AbstractEasySql;
import org.zizi.db.plan.plan.PostgresqlResultPlan;
import org.zizi.db.tool.impl.PostgresqlEasySqlTool;

public class PostgresqlEasySql extends AbstractEasySql
{
	public PostgresqlEasySql()
	{
		plan = new PostgresqlResultPlan(charset);
		tool = new PostgresqlEasySqlTool();
	}
	
	public <T> List<T> page(Class<T> type, int offset, int limit, String sql, Object... parameters) throws Exception
	{
		log.debug("分页查询: " + sql);

		String sql2 = "select * from (" + sql + ") esql_t offset ? limit ?";

		int n = parameters.length;
		Object[] parameters2 = Arrays.copyOf(parameters, n + 2);
		parameters2[n] = offset;
		parameters2[n + 1] = limit;

		return list(type, sql2, parameters2);
	}

	protected void setParameters(PreparedStatement ps, Object... parameters) throws Exception
	{
		int count = ps.getParameterMetaData().getParameterCount();
		for (int i = 0; i < count; i++)
		{
			Object o = parameters[i];
			if (o instanceof Boolean) o = ((Boolean) o).booleanValue() ? 1 : 0;
			else if (o instanceof String) o = charset.encodeToDatabase((String)o);
			
			int type = ps.getParameterMetaData().getParameterType(i + 1);
			ps.setObject(i + 1, o, type);
		}
	}

	public String getTableInfoSql(String table)
	{
		return "select * from " + table + " limit 1";
	}
}
